package com.njust.RateMyTray_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njust.RateMyTray_backend.common.CustomException;
import com.njust.RateMyTray_backend.common.ForbiddenException;
import com.njust.RateMyTray_backend.common.ResourceNotFoundException;
import com.njust.RateMyTray_backend.dto.FavoriteCreateDTO;
import com.njust.RateMyTray_backend.entity.Favorite;
import com.njust.RateMyTray_backend.mapper.FavoriteMapper;
import com.njust.RateMyTray_backend.service.FavoriteService;
import com.njust.RateMyTray_backend.service.ValidationService;
import com.njust.RateMyTray_backend.vo.FavoriteVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class FavoriteServiceImpl extends ServiceImpl<FavoriteMapper, Favorite> implements FavoriteService {

    @Autowired
    private ValidationService validationService;

    @Override
    public Favorite addFavorite(Long userId, FavoriteCreateDTO createDTO) {
        // 1. 验证目标是否存在
        validationService.validateTargetExists(createDTO.getTargetType(), createDTO.getTargetId());

        // 2. 检查是否已收藏
        LambdaQueryWrapper<Favorite> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Favorite::getOwnerId, userId)
                .eq(Favorite::getTargetType, createDTO.getTargetType())
                .eq(Favorite::getTargetId, createDTO.getTargetId());
        if (this.count(queryWrapper) > 0) {
            throw new CustomException("您已收藏过此项目");
        }

        // 3. 创建收藏记录
        Favorite favorite = new Favorite();
        favorite.setOwnerId(userId);
        favorite.setTargetType(createDTO.getTargetType());
        favorite.setTargetId(createDTO.getTargetId());
        favorite.setCreatedAt(LocalDateTime.now());
        this.save(favorite);

        return favorite;
    }

    @Override
    public void removeFavorite(Long userId, Long favoriteId) {
        Favorite favorite = this.getById(favoriteId);
        if (favorite == null) {
            throw new ResourceNotFoundException("收藏记录不存在");
        }
        if (!favorite.getOwnerId().equals(userId)) {
            throw new ForbiddenException("无权限删除他人的收藏");
        }
        this.removeById(favoriteId);
    }

    @Override
    public List<FavoriteVO> getFavorites(Long userId, String targetType) {
        List<FavoriteVO> favorites = new ArrayList<>();
        if (targetType == null || "dish".equalsIgnoreCase(targetType)) {
            favorites.addAll(baseMapper.findFavoriteDishesByUserId(userId));
        }
        if (targetType == null || "window".equalsIgnoreCase(targetType)) {
            favorites.addAll(baseMapper.findFavoriteWindowsByUserId(userId));
        }
        return favorites;
    }
    
} 